/*
 * @Author: cl
 * @Description: 自动加载路由
 * @Date: 2023-05-15 16:41:41
 * @LastEditTime: 2023-07-05 14:22:50
 * @FilePath: \vue3scaffold\src\router\autoload.ts
 * @LastEditors: chenli chenli@kcwl.com
 */
import { RouteRecordRaw } from "vue-router";
import {env}  from '@/utils/helper'
const layouts = import.meta.glob("../layout/*.vue", { eager: true });
const childlayouts = import.meta.glob("../views/**/*.vue", { eager: true });

export function getLayoutRouter() {
  const routers = [] as RouteRecordRaw[];
  Object.entries(layouts).forEach(([file, module]) => {
    const route = getRouteByModule(file, module as any);
    route.children = getChildRouter(route);
    routers.push(route);
  });
  return routers;
}

function getChildRouter(layoutRoute: RouteRecordRaw) {
  const routers = [] as RouteRecordRaw[];
  Object.entries(childlayouts).forEach(([file, module]) => {
    if (file.includes(`../views/${layoutRoute.name as string}`)) {
      const route = getRouteByModule(file, module as any);
      routers.push(route);
    }
  });
  return routers;
}

function getRouteByModule(file: string, module: { [key: string]: any }) {
  // const name = file.split("/").pop()?.split(".")[0];
  const name = file.replace(/.+layout\/|.+views\/|\.vue/gi,'')
  const route = {
    name:name.replace("/","-"),
    path: `/${name}`,
    component: module.default,
  } as RouteRecordRaw;
  return route;
}
// console.log(env.VITE_ROUTE_AUTOLOAD,env.VITE_SOME_KEY);

const routers = env.VITE_ROUTE_AUTOLOAD? getLayoutRouter(): [] as RouteRecordRaw[]
 export default routers
